<?php
namespace app\controllers;

use app\models\Mobile;
use app\models\MobileBorrow;
use mvc\helpers\Tool;
use mvc\web\Controller;
use mvc\web\Pagination;

class MobileBorrowController extends Controller
{
    public function actionIndex()
    {
        $model = new MobileBorrow();

        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $pagination = new Pagination($model->count(), $page);

        $data = $model
            ->select("mobile_borrow.*,mobile.models,mobile.unique_number,mobile.mobile_unique_number,mobile.os")
            ->join(Mobile::tableName(), ' on mobile_borrow.mobile_id=mobile.id')
            ->limit("$pagination->offset,$pagination->limit")
            ->orderBy('borrow_time DESC')
            ->all();

        return $this->render('index', [
            'pagination' => $pagination,
            'data' => $data,
        ]);
    }

    public function actionCreate()
    {
        if (Tool::isAjax()) {
            $data = $_POST;
            $data['borrow_time'] = date('Y-m-d');
            $model = new MobileBorrow();
            if ($model->insert($data)) {
                $model2 = new Mobile();
                $model2->where("id=$data[mobile_id]")->update([
                    'status' => 2
                ]);
                $this->jsonResponse(['status' => 1]);
            } else {
                $this->jsonResponse(['status' => 0, 'msg' => $model->getHeadError()]);
            }
        }

        return $this->render('create', [

        ]);
    }

    public function actionReturn()
    {
        if (Tool::isAjax()) {
            $data = $_POST;
            unset($data['borrowId']);
            $model = new MobileBorrow();
            if ($model->where("id=$_POST[borrowId]")->update(['status' => 1, 'actual_return_time' => date('Y-m-d')])) {
                $model2 = new Mobile();
                $model2->where("id=$_POST[mobile_id]")->update(['status' => 1]);
                $this->jsonResponse(['status' => 1]);
            } else {
                $this->jsonResponse(['status' => 0, 'msg' => $model->getHeadError()]);
            }
        }
    }
}